package com.fangzhi.controller;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fangzhi.mobel.AdminAccountInfo;
import com.fangzhi.mobel.enums.GlobalCodeEnum;
import com.fangzhi.mobel.io.LoginIo;
import com.fangzhi.mobel.vo.LoginVo;
import com.fangzhi.service.AdminAccountInfoService;
import com.fangzhi.service.AdminAccountRoleDeptRelationService;
import com.fangzhi.utils.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Wrapper;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AdminAccountInfoService adminAccountInfoService;
    @Autowired
    private AdminAccountRoleDeptRelationService adminAccountRoleDeptRelationService;

    /**
     * 登录
     * @return
     */
    @PostMapping("/login")
    public ResponseResult login(@RequestBody LoginIo io, HttpServletResponse response){
        String decrypt = AESUtil.decrypt(io.getPassword());
        AdminAccountInfo one = adminAccountInfoService.getOne(Wrappers.<AdminAccountInfo>lambdaQuery()
                .eq(AdminAccountInfo::getUserCode, io.getUserCode())
                .eq(AdminAccountInfo::getPassword, decrypt)
                .eq(AdminAccountInfo::getStatus, 1));
        if (null == one)
            return ResponseResult.systemException(GlobalCodeEnum.GL_FAIL_9998);

        String token = JwtUtil.createToken(one.getUserCode());
        LoginVo loginVo = BeanCopyUtil.copyProperties(one, LoginVo.class);

        LoginVo loginVoRole = adminAccountRoleDeptRelationService.queryRoleNameByAccountId(loginVo.getId());
        loginVo.setFangzhi(token).setRoleId(loginVoRole.getRoleId()).setRoleName(loginVoRole.getRoleName());
        stringRedisTemplate.opsForValue().set(token, JSON.toJSONString(loginVo), 60 * 60 * 24 * 2, TimeUnit.SECONDS);
        response.setHeader(GlobalParam.COOKIE_VALUE, token);

        return ResponseResult.OK(loginVo);
    }

    /**
     * 登出
     * @return
     */
    @GetMapping("/logout")
    public ResponseResult logout(HttpServletRequest request){
        String cookie = request.getHeader(GlobalParam.COOKIE_VALUE);
        stringRedisTemplate.delete(cookie);
        return ResponseResult.OK();
    }
}
